<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------

namespace app\admin\controller;

use \think\Cache;
use \think\Controller;
use think\Loader;
use think\Db;
use \think\Cookie;
use app\admin\controller\User;
use app\admin\model\Article as articleModel;
use app\admin\model\ArticleCate as cateModel;


class Article extends User
{
    public function index()
    {
        $model = new articleModel();
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        $wherelist = [];
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['title'] = ['like', '%' . $post['keywords'] . '%'];
            $wherelist['keywords'] = $post['keywords'];
        }
        if (isset($post['article_cate_id']) and $post['article_cate_id'] > 0) {
            $where['article_cate_id'] = $post['article_cate_id'];
            $wherelist['article_cate_id'] = $post['article_cate_id'];
        }
        if (isset($post['admin_id']) and $post['admin_id'] > 0) {
            $where['admin_id'] = $post['admin_id'];
            $wherelist['admin_id'] = $post['admin_id'];
        }
        if (isset($post['status']) and ($post['status'] == 1 or $post['status'] === '0')) {
            $where['status'] = $post['status'];
            $wherelist['status'] = $post['status'];
        }
        if (isset($post['is_top']) and ($post['is_top'] == 1 or $post['is_top'] === '0')) {
            $where['is_top'] = $post['is_top'];
            $wherelist['is_top'] = $post['is_top'];
        }
        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
            $wherelist['create_time'] = $post['create_time'];
        }
        $articles = empty($where) ? $model->order('sort_num desc,create_time desc')->paginate(20) : $model->where($where)->order('sort_num desc,create_time desc')->paginate(20);
        //添加最后修改人的name
        foreach ($articles as $key => $value) {
            $articles[$key]['edit_admin'] = Db::name('admin')->where('id',$value['edit_admin_id'])->value('nickname');
        }
        $this->assign('articles',$articles);
        $info['cate'] = Db::name('article_cate')->select();
        $info['admin'] = Db::name('admin')->select();
        $this->assign('info',$info);
        $this->assign('wherelist',$wherelist);
        return $this->fetch();
    }

    public function publish()
    {
        //获取菜单id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new articleModel();
        $cateModel = new cateModel();
        //是正常添加操作
        if($id > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['title', 'require', '标题不能为空'],
                    ['article_cate_id', 'require', '请选择分类'],
                    ['thumb', 'require', '请上传缩略图'],
                    ['content', 'require', '文章内容不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证菜单是否存在
                $article = $model->where('id',$id)->find();
                if(empty($article)) {
                    return $this->error('id不正确');
                }
                //设置修改人
                $post['edit_admin_id'] = Cookie::get('admin');
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    addlog($model->id);//写入日志
                    return $this->success('修改成功','admin/article/index');
                }
            } else {
                //非提交操作
                $article = $model->where('id',$id)->find();
                $cates = $cateModel->select();
                $cates_all = $cateModel->catelist($cates);
                $this->assign('cates',$cates_all);

                $city_where['type'] = "CITY";
                $city_where['deleted'] = 0;
                $city = Db::name("city")->where($city_where)->field("id,name")->select();
                $this->assign('city',$city);

                //商品的订单类型
                $orderType = array(
                    array('id'=>'Ticket_FIT','name'=>'地接社标品'),
                    array('id'=>'Ticket_POI','name'=>'门票类产品'),
                    array('id'=>'Hotel','name'=>'酒店'),
                    array('id'=>'Custom','name'=>'定制产品'),
                    array('id'=>'Vehicle','name'=>'用车'),
                    array('id'=>'Ticket_AIR','name'=>'机票'),
                    array('id'=>'Rental_Device','name'=>'物品购买/租赁'),
                    array('id'=>'Other','name'=>'其它'),
                    array('id'=>'Price_Gap','name'=>'补差价'),
                    array('id'=>'Self_Drive','name'=>'自驾游'),
                    array('id'=>'Personal_Tailor','name'=>'私人定制服务'),
                    array('id'=>'Subscription','name'=>'代订服务'),
                );
                $this->assign('orderType',$orderType);

                if(!empty($article)) {
                    //城市
                    if(!empty($article['city_id']) && !in_array($article['city_id'],['999999','8888','7777'])){
                        $city_id_str = $article['city_id'];
                        $city_id_arr = explode(",",$city_id_str);
                        $cityArr = [];
                        foreach ($city as $c_v) {
                            $cityArr[$c_v['id']] = $c_v['name'];
                        }
                        $city_name_arr = array();
                        foreach ($city_id_arr as $n_v) {
                            if(isset($cityArr[$n_v])){
                                $city_name_arr[] = ['id'=>$n_v,'name'=>$cityArr[$n_v]];
                            }
                        }
                        $this->assign('city_name',$city_name_arr);
                    }else{
                        $this->assign('city_name',$article['city_id']);
                    }
                    //POI
                    $pois = [];
                    if(!empty($article['poi_ids'])){
                        $pois = db('poi')->field('id,name')
                            ->where(['id'=>['in',$article['poi_ids']]])
                            ->select();
                    }
                    $this->assign('pois',$pois);

                    //订单类型
                    if(!empty($article['orderType']) && $article['orderType']!=='999999'){
                        $orderType_str = $article['orderType'];
                        $orderType_arr = explode(",",$orderType_str);
                        $orderTypeArr = [];
                        foreach ($orderType as $c_v) {
                            $orderTypeArr[$c_v['id']] = $c_v['name'];
                        }
                        $orderType_name_arr = array();
                        foreach ($orderType_arr as $n_v) {
                            $orderType_name_arr[] = ['id'=>$n_v,'name'=>$orderTypeArr[$n_v]];
                        }
                        $this->assign('orderType_name',$orderType_name_arr);
                    }else{
                        if($article['orderType']=='999999'){
                            $orderType_name_arr = '999999';
                            $this->assign('orderType_name',$orderType_name_arr);
                        }
                    }
                    $poilist = db('poi')->field('id,name')->where(['deleted'=>0])->select();
                    $this->assign('poilist',$poilist);
                    $this->assign('article',$article);
                    return $this->fetch();
                } else {
                    return $this->error('id不正确');
                }
            }
        }else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['title', 'require', '标题不能为空'],
                    ['article_cate_id', 'require', '请选择分类'],
                    ['thumb', 'require', '请上传缩略图'],
                    ['content', 'require', '文章内容不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //设置创建人
                $post['admin_id'] = Cookie::get('admin');
                //设置修改人
                $post['edit_admin_id'] = $post['admin_id'];
                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加失败');
                } else {
                    addlog($model->id);//写入日志
                    return $this->success('添加成功','admin/article/index');
                }
            } else {
                //非提交操作
                $city_where['type'] = "CITY";
                $city_where['deleted'] = 0;
                $city = Db::name("city")->where($city_where)->field("id,name")->select();
                $this->assign('city',$city);
                $poilist = db('poi')->field('id,name')->where(['deleted'=>0])->select();
                $this->assign('poilist',$poilist);
                //商品的订单类型
                $orderType = array(
                    array('id'=>'Ticket_FIT','name'=>'地接社标品'),
                    array('id'=>'Ticket_POI','name'=>'门票类产品'),
                    array('id'=>'Hotel','name'=>'酒店'),
                    array('id'=>'Custom','name'=>'定制产品'),
                    array('id'=>'Vehicle','name'=>'用车'),
                    array('id'=>'Ticket_AIR','name'=>'机票'),
                    array('id'=>'Rental_Device','name'=>'物品购买/租赁'),
                    array('id'=>'Other','name'=>'其它'),
                    array('id'=>'Price_Gap','name'=>'补差价'),
                    array('id'=>'Self_Drive','name'=>'自驾游'),
                    array('id'=>'Personal_Tailor','name'=>'私人定制服务'),
                    array('id'=>'Subscription','name'=>'代订服务'),
                );
                $this->assign('orderType',$orderType);

                $cate = $cateModel->select();
                $cates = $cateModel->catelist($cate);
                $this->assign('cates',$cates);
                return $this->fetch();
            }
        }
    }

    public function delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('article')->where('id',$id)->delete()) {
                return $this->error('删除失败');
            } else {
                addlog($id);//写入日志
                return $this->success('删除成功','admin/article/index');
            }
        }
    }

    // 是否显示
    public function is_show(){
        $id= input('id');
        $is_show= input('is_show');
        if (!empty($id)){
            if (false ==  db('article')->where('id',$id)->update(['is_show'=>$is_show]) ){
                return $this->error('修改失败');
            }else{
                return $this->success('修改成功','admin/article/index');
            }
        }else{
            return $this->error('修改失败');
        }
    }

    public function is_top()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            if(false == Db::name('article')->where('id',$post['id'])->update(['is_top'=>$post['is_top']])) {
                return $this->error('设置失败');
            } else {
                addlog($post['id']);//写入日志
                return $this->success('设置成功','admin/article/index');
            }
        }
    }

    public function status()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            if(false == Db::name('article')->where('id',$post['id'])->update(['status'=>$post['status']])) {
                return $this->error('设置失败');
            } else {
                addlog($post['id']);//写入日志
                return $this->success('设置成功','admin/article/index');
            }
        }
    }


    //引入模板
    public function inc_tmplet(){
        //模板ID暂时
        $id = 20;
        $content = db("article")->where('id',$id)->field("content")->find();

        return $this->success('查询成功','',$content['content']);
    }


    //绑定推荐浏览
    public function recommend()
    {
        $date = db("article_binduser")
            ->alias('a')
            ->join('member m','a.member_id=m.member_id','left')
            ->join('article c','a.article_id=c.id','left')
            ->field('a.id,m.member_nickname,c.id as article_id,c.title')
            ->order('a.creattime desc')->select();

        $this->assign('bind',$date);
        return $this->fetch();
    }


    //用户推荐绑定
    public function binduser()
    {
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();
            $da = db('article_binduser')->insert([
                'member_id'=>$post['member_id'],
                'article_id'=>$post['article_id'],
                'creattime'=>time(),
            ]);
            if ($da){
                return $this->success('添加成功');
            }else{
                return $this->error('添加失败');
            }
        } else {
            //非提交操作
            $article = db("article")->where('status',1)->field("id,title")->order("create_time desc")->select();
            $this->assign('article',$article);

            $where['is_test'] = 0;
            $member = Db::name("member")->where($where)->field("member_id as id,member_nickname as name")->select();
            $this->assign('member',$member);

            return $this->fetch();
        }
    }


    //删除客户绑定的攻略推送
    public function deletebind(){
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if(false == Db::name('article_binduser')->where('id',$id)->delete()) {
                return $this->error('删除失败');
            } else {
                return $this->success('删除成功');
            }
        }
    }

    //修改权重
    public function updArticleSortNum()
    {
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();
            if(isset($post['id'])&&!empty($post['id'])){
                $article = db("article")->where(['id'=>$post['id']])->find();
                if(!empty($article)){
                    $res = db("article")->where(['id'=>$post['id']])->update(['sort_num'=>$post['num']]);
                    if($res!==false){
                        return $this->success('更新成功');
                    }else{
                        return $this->error('更新失败');
                    }
                }else{
                    return $this->error('更新失败');
                }
            }else{
                return $this->error('更新失败');
            }
        }else{
            return $this->error('更新失败');
        }

    }


}
